<?php
declare(strict_types=1);

namespace app\index\controller\api;

use \Swoole\Http\Request;
use \Swoole\Http\Response;

class Netbar {
    public \lib\User $user;
    public \lib\Merchant $merchant;
    public $middleware = [
        \lib\middleware\NetbarAuth::class=>[]
    ];

    public function read(Request $request, Response $response)
    {
        $mid = $this->merchant->id;
        $db = new \sys\Db();
        $merchant = $db->table('tp_merchant')->where([['id','=',$mid]])->field(['id','merchant_name', 'area', 'm_address', 'tel', 'baidu', '`desc`'])->find();

        $license = $db->table('tp_nb_merchant_goods_license')->where([['mid','=',$mid]])->find();
        if(is_null($license)){
            if($db->table('tp_nb_merchant_goods_license')->insert(['mid'=>$mid])){
                $license = $db->table('tp_nb_merchant_goods_license')->where([['mid','=',$mid]])->find();
            }
        }
        
        $bank = $db->table('tp_nb_merchant_goods_bankcard')->where([['mid','=',$mid],['active','=',1]])->find();
        if(is_null($bank)){
            if($db->table('tp_nb_merchant_goods_bankcard')->insert(['mid'=>$mid])){
                $bank = $db->table('tp_nb_merchant_goods_bankcard')->where([['mid','=',$mid]])->find();
            }
        }
        
        $mer = $db->table('tp_nb_merchant_goods')->where([['id','=',$mid]])->field("id,amount_online,shift_id,cashout_password")->find();
        $mer['cashout_password'] = !empty($mer['cashout_password']);

        return ['success'=>true,'base'=>$merchant, 'license'=>$license,'bank'=>$bank,'merchant'=>$mer];
    }

    public function setPassword(Request $request, Response $response){
        $post = json_decode($request->getContent(), true);
        $checker = validate([
            'password'=>'require',
            'repassword'=>'confirm:password'
        ])->check($post);
        if(!$checker->pass()) return $checker->jsonSerialize();

        $mid = $this->merchant->id;
        $db = new \sys\Db();
        $row = $db->table('tp_nb_merchant_goods')->where([['id','=',$mid]])->find();

        if(empty($row['cashout_password'])){
            $oldValue = [];
            if(null !== ($changed = $this->merchant->update(['cashout_password'=>$post['password']], false, $oldValue))){
                $db->table('tp_nb_merchant_goods')->where([['id','=',$mid]])->update(['cashout_password'=>$post['password']]);
                return ['success'=>true,'message'=>'提现密码设置成功！'];
            }
        }

        return ['success'=>false,'message'=>'提现密码设置失败！'];
    }

    public function license(Request $request, Response $response)
    {
        $post = json_decode($request->getContent(), true);

        $checker = validate([
            'license_photo|营业执照'            =>'require',
            'license_number|营业执照编号'       =>'require',
            'license_name|营业执照名称'         =>'require',
            'license_address|营业执照注册地址'  =>'require',
            'idcard_front_photo|法人身份证'     =>'require',
            'idcard_back_photo|法人身份证'      =>'require',
            'user_photo|手持身份证'             =>'require',
            'tel'                              =>'require|tel',
            'checked'                          =>'require|boolean'
        ])->check($post);
        if(!$checker->pass()) return json($checker->jsonSerialize());

        if(!$post['checked']){
            $check = validate([
                'contacts_idcard_front_photo|联系人身份证'=>'require',
                'contacts_idcard_back_photo|联系人身份证'=>'require',
                'contacts_user_photo|手持身份证'=>'require',
                'contacts_name|联系人姓名'=>'require|nospace',
                'contacts_idcard|联系人'=>'require|idcard',
                'authorize_photo|商户委托书'=>'require'
            ])->check($post);
            if(!$check->pass()) return json($check->jsonSerialize());
        }

        $mid = $this->merchant->id;
        $db = new \sys\Db();
        $row = $db->table('tp_nb_merchant_goods_license')->where([['mid','=', $mid]])->find();

        if($row['stage'] == 2)
            return ['success'=>false,'message'=>'已审核,不能继续提交.'];
        
        $keys  = ['license_photo','idcard_front_photo','idcard_back_photo','user_photo'];
        $allowField = [
            'license_photo','license_number','license_name','license_address',
            'idcard_front_photo','idcard_back_photo','user_photo','tel'
        ];

        if(!$post['checked']){
            $keys = array_merge($keys,[
                        'contacts_idcard_front_photo','contacts_idcard_back_photo',
                        'contacts_user_photo','authorize_photo'
                    ]);
            $allowField = array_merge($allowField,[
                                'contacts_idcard_front_photo','contacts_idcard_back_photo',
                                'contacts_user_photo','contacts_name','contacts_idcard','authorize_photo'
                            ]);
        }

        $update = [
            'stage'        => 1,
            'upload_time'  => time(),
        ];

        foreach($allowField as $v){
            $update[$v] = $post[$v];
        }

        if($db->table('tp_nb_merchant_goods_license')->where([['mid','=', $mid]])->update($update)){
            foreach($keys as $val){

                if(!empty($row[$val]) && $row[$val] != $update[$val]){
                    \lib\ExtiStorage::delete($row[$val]);
                }
                
                \lib\ExtiStorage::setmeta($update[$val],null);
            }

            return ['success'=>true,'message'=>'提交成功,请等待审核.'];
        }

        return ['success'=>false,'message'=>'提交失败.'];
    }

    public function bankcard(Request $request, Response $response)
    {
        $post = json_decode($request->getContent(), true);
        $checker = validate([
            'bank_card'             =>'require|length:15,19',
            'bank_type'             =>'require',
            'idcard_back_photo'     =>"require",
            'idcard_front_photo'    =>"require",
            'owner_bank'            =>"require|chs",
            'owner_idcard|持卡人'   =>"require|idcard",
            'owner_name'            =>"require|chs",
            'tel'                   =>'require|tel',
            'user_photo'            =>'require',
            'agreement_photo'       =>'require',
            'bank_front_photo'      =>'require',
            'bank_back_photo'       =>'require',
            'checked'               =>'require|boolean'
        ])->check($post);
        if(!$checker->pass()) return $checker->jsonSerialize();

        if(!$post['checked'] && empty($post['authorize_photo'])){
            return ['success'=>false,'message'=>'请提交商户委托书.'];
        }

        $mid = $this->merchant->id;
        $db = new \sys\Db();
        $row = $db->table('tp_nb_merchant_goods_bankcard')->where([['mid','=', $mid]])->find();

        if($row['stage'] == 2)
            return ['success'=>false,'message'=>'已审核,不能继续提交.'];

        $keys  = ['agreement_photo','idcard_front_photo','idcard_back_photo','user_photo','bank_front_photo','bank_back_photo'];
        $allowField = [
            'bank_card','bank_type',
            'idcard_back_photo','idcard_front_photo',
            'owner_bank','owner_idcard','owner_name',
            'tel','user_photo',
            'agreement_photo','bank_front_photo','bank_back_photo',
        ];

        if(!$post['checked']){
            $keys = array_merge($keys,['authorize_photo']);
            $allowField = array_merge($allowField,['authorize_photo']);
        }

        $ip = $request->header['x-real-ip'] ?? $request->server['remote_addr'];
        $update = [
            'stage'        => 1,
            'upload_time'  => time(),
            'ip'           => $ip
        ];

        foreach($allowField as $v){
            $update[$v] = $post[$v];
        }

        if($db->table('tp_nb_merchant_goods_bankcard')->where([['mid','=', $mid]])->update($update)){
            foreach($keys as $val){
                if(!empty($row[$val]) && $row[$val] != $update[$val]){
                    \lib\ExtiStorage::delete($row[$val]);
                }
                
                \lib\ExtiStorage::setmeta($update[$val],null);
            }

            return ['success'=>true,'message'=>'提交成功,请等待审核.'];
        }

        return ['success'=>false,'message'=>'提交失败.'];
    }
}